import 'package:flutter/material.dart';
import 'dart:ui';

Future<void> main() async {
  // 被 Flutter 捕获的错误
  // await myErrorsHandler.initialize();
  FlutterError.onError = (details) {
    FlutterError.presentError(details);
    print('捕获到的错误: ${details.toString()}');
    // myErrorsHandler.onErrorDetails(details);
  };
  // 未被捕获的错误
  PlatformDispatcher.instance.onError = (error, stack) {
    // myErrorsHandler.onError(error, stack);
    print('未被捕获的错误: ${error.toString()}, ${stack.toString()}');
    return true;
  };
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 自定义布局错误时显示的界面
      // 默认是红色区域
      builder: (context, widget) {
        Widget error = const Text('...rendering error...');
        if (widget is Scaffold || widget is Navigator) {
          error = Scaffold(body: Center(child: error));
        }
        ErrorWidget.builder = (errorDetails) => error;
        if (widget != null) return widget;
        throw ('widget is null');
      },
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  late int a;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('错误处理')),
      body: Center(
        child: Text('something wrong $a'),
      ),
    );
  }
}
